<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { onMounted, ref } from 'vue'
import { Socket, io } from 'socket.io-client'
import { onUnmounted } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enum/index'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import { nextTick } from 'vue'
import dayjs from 'dayjs'
import { showToast } from 'vant'
import { provide } from 'vue'

const store = useUserStore()
const route = useRoute()

// 所有消息的数组
const list = ref<Message[]>([])
const consult = ref<ConsultOrderItem>()

// 1. 建立和关闭socket连接
let socket: Socket
onMounted(() => {
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  // 1.1 监听是否建立成功
  socket.on('connect', () => {
    // 建立连接成功
    console.log('建立连接成功...')
    list.value = []
  })

  // 1.2 监听错误
  socket.on('error', (event) => {
    // 错误异常消息
    console.log('error', event)
  })

  // 1.3 监听关闭
  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('disconnect')
  })
})

onUnmounted(() => {
  socket.close()
})

// 2. 接收聊天记录
onMounted(() => {
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // 2.1 处理拿到的消息
    const arr: Message[] = []
    data.forEach((item, i) => {
      // ------
      // 拿到消息分组数组中的第一个消息分组的创建时间(作为一个时间参照去获取更早的消息分组)
      if (i === 0) time.value = item.createTime
      // -------
      // 2.2 取出消息分组的时间生成一条消息放入数组的最前面
      arr.push({
        id: item.createTime,
        msgType: MsgType.Notify,
        createTime: item.createTime,
        msg: {
          content: item.createTime
        },
        noScroll: initMsg.value === false
      })
      // 2.3 把其它的消息取出放入数组
      // arr.push(...item.items)
      item.items.forEach((obj) => {
        arr.push({ noScroll: initMsg.value === false, ...obj })
      })
    })
    // 2.4 把处理好的消息放入消息数组
    list.value.unshift(...arr)
    console.log(list.value)

    // ----------------------------------------------
    // 2.5 关闭刷新效果
    loading.value = false
    // 2.6 判断是否有更早的数据
    if (data.length === 0) {
      return showToast('没有聊天记录了...')
    }
    // 2.7 判断是否是初始获取聊天记录
    // 只有是初始获取, 才会滚动到最底部
    if (initMsg.value) {
      console.log('第一次获取历史聊天记录')
      nextTick(() => {
        initMsg.value = false // 不是第一次了
        // 标明消息已读
        socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        window.scrollTo(0, document.body.scrollHeight)
      })
    }
  })
})

// 3. 根据订单id获取订单详情
onMounted(async () => {
  // 3.1 调用接口
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data

  // 3.2 监听订单状态改变
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })
})

// 4. 发送文字消息
const sendText = (text: string) => {
  // 4.1 把消息发送给服务器
  socket.emit('sendChatMsg', {
    from: store.user?.id, // 发送人的id
    to: consult.value?.docInfo?.id, // 接收人(医生)的id
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}

onMounted(() => {
  // 4.2 接收服务端推送的消息
  socket.on('receiveChatMsg', async (msg: Message) => {
    // 往消息数组的尾部追加一条消息
    list.value.push(msg)
    // 让消息列表滚动到最底部
    await nextTick()
    // 让消息已读 - 最新的消息id
    socket.emit('updateMsgStatus', msg.id)
    window.scrollTo(0, document.body.scrollHeight)
  })
})

// 5. 发送图片
const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id, // 发送人的id
    to: consult.value?.docInfo?.id, // 接收人(医生)的id
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}

// 6. 下拉加载历史聊天记录
const loading = ref(false)
const time = ref(dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')) // YYYY-MM-DD HH:mm:ss
const initMsg = ref(true) // 记录是否是初始聊天 true-是 false-不是
const onRefresh = () => {
  console.log('触发下拉刷新')
  //向socket服务端发送数据 参数：pageSize: number, lastTime: string, orderId: string
  socket.emit('getChatMsgList', 5, time.value, route.query.orderId)
}

// 7. 向子组件注入数据
provide('consult', consult)

const completeEva = (score: number) => {
  // 找到未评价的数据对象
  const obj = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (obj) {
    // 修改数据对象的消息类型
    obj.msgType = MsgType.CardEva
    // 添加评价消息
    obj.msg.evaluateDoc = {
      score
    }
  }
}
provide('completeEva', completeEva)
</script>

<template>
  <div class="room-page">
    <!-- 导航条 -->
    <cp-nav-bar title="医生问诊室"></cp-nav-bar>
    <RoomStatus
      :status="consult?.status"
      :countdown="consult?.countdown"
    ></RoomStatus>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <RoomMessage :list="list"></RoomMessage>
    </van-pull-refresh>
    <RoomAction
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    ></RoomAction>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
